import shutil
import os


def copy_files(source_dir, target_dir):
    """
    复制 source_dir 目录下的所有文件到 target_dir 目录，
    如果文件已存在则替换。

    :param source_dir: 源目录路径
    :param target_dir: 目标目录路径
    """
    if not os.path.exists(source_dir):
        raise FileNotFoundError(f"Source directory '{source_dir}' does not exist")

    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    for item in os.listdir(source_dir):
        source_path = os.path.join(source_dir, item)
        target_path = os.path.join(target_dir, item)

        if os.path.isfile(source_path):
            shutil.copy2(source_path, target_path)
        elif os.path.isdir(source_path):
            if os.path.exists(target_path):
                shutil.rmtree(target_path)
            shutil.copytree(source_path, target_path)


def copy_word_excel_files(source_dir, target_dir):
    """
    复制 source_dir 目录下的所有 Word 和 Excel 文件到 target_dir 目录，
    如果文件已存在则替换。

    :param source_dir: 源目录路径
    :param target_dir: 目标目录路径
    """
    if not os.path.exists(source_dir):
        raise FileNotFoundError(f"Source directory '{source_dir}' does not exist")

    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    # 定义需要复制的文件扩展名
    file_extensions = ('.doc', '.docx', '.xls', '.xlsx')

    for root, _, files in os.walk(source_dir):
        for file in files:
            if file.endswith(file_extensions):
                source_path = os.path.join(root, file)
                relative_path = os.path.relpath(source_path, source_dir)
                target_path = os.path.join(target_dir, relative_path)

                target_dir_path = os.path.dirname(target_path)
                if not os.path.exists(target_dir_path):
                    os.makedirs(target_dir_path)

                shutil.copy2(source_path, target_path)


def get_word_excel_files(target_dir):
    """
    获取 target_dir 目录下的所有文件名，并根据文件类型（Word 和 Excel）分类到两个列表中，
    不在这两类的文件都舍弃掉。

    :param target_dir: 目标目录路径
    :return: 一个包含两个列表的元组，第一个列表为 Word 文件名，第二个列表为 Excel 文件名
    """
    if not os.path.exists(target_dir):
        raise FileNotFoundError(f"Target directory '{target_dir}' does not exist")

    word_files = []
    excel_files = []

    # 定义文件扩展名
    word_extensions = ('.doc', '.docx')
    excel_extensions = ('.xls', '.xlsx')

    for root, _, files in os.walk(target_dir):
        for file in files:
            if file.endswith(word_extensions):
                word_files.append(file)
            elif file.endswith(excel_extensions):
                excel_files.append(file)

    return word_files, excel_files


def rename_files(target_dir, old_str, new_str):
    """
    重命名 target_dir 目录下所有文件名，将文件名中的 old_str 部分替换为 new_str，
    不匹配的不替换。

    :param target_dir: 目标目录路径
    :param old_str: 需要替换的字符串
    :param new_str: 替换后的字符串
    """
    if not os.path.exists(target_dir):
        raise FileNotFoundError(f"Target directory '{target_dir}' does not exist")

    for root, _, files in os.walk(target_dir):
        for file in files:
            if old_str in file:
                old_file_path = os.path.join(root, file)
                new_file_name = file.replace(old_str, new_str)
                new_file_path = os.path.join(root, new_file_name)
                os.rename(old_file_path, new_file_path)
                print(f'Renamed: {old_file_path} -> {new_file_path}')


# if __name__ == "__main__":
#     target_dir = 'target'
#     old_str = '+++++'
#     new_str = '辽宁石油化工'
#     rename_files(target_dir, old_str, new_str)

if __name__ == "__main__":
    target_dir = 'target'
    word_files, excel_files = get_word_excel_files(target_dir)

    print("Word Files:")
    for file in word_files:
        print(file)

    print("\nExcel Files:")
    for file in excel_files:
        print(file)

# if __name__ == "__main__":
#     source_dir = 'source'
#     target_dir = 'target'
#     copy_word_excel_files(source_dir, target_dir)

#
# if __name__ == "__main__":
#     source_dir = 'source'
#     target_dir = 'target'
#     copy_files(source_dir, target_dir)
